﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;

namespace onPulse01
{
    public class GoogleConnect
    {
        private AppSettings settings = new AppSettings();

        private string accountType = "HOSTED_OR_GOOGLE";
        private string service = "health";
        private string source = "onPulse-health-phone-app-1.0";

        private string email = "";
        private string password = "";
        private string profile_id = "";

        string AuthenticationToken = "";
        string post_data = "";
        private string ccr_string_response = "";

        public event GoogleGetHandler getEvent;
        public event GooglePostHandler postEvent;

        #region Links
        string link_client_login = "https://www.google.com/accounts/ClientLogin";
        string link_profiles = "https://www.google.com/health/feeds/profile/list";
        string link_base_profile_ui = "https://www.google.com/health/feeds/profile/ui/";
        string link_full_ccr = "";
        string link_labtest = "";
        #endregion
        string link = "";

        public GoogleConnect()
        {
            email = settings.Email;
            password = settings.Password;
            profile_id = settings.ProfileId;

            link_full_ccr = link_base_profile_ui + profile_id;
            link_labtest = link_base_profile_ui + profile_id + "/-/Labtest";
        }

        //get profiles
        public void GetProfiles()
        {
            link = link_profiles;
            authenticate();
        }

        //get results 
        public void GetResults()
        {
            link = link_labtest;
            authenticate();
        }

        //post new blood presure result 
        public void PostBloodPresure(int systolic, int diastolic, string date)
        {
            string title = "[onPulse] Blood pressure";
            string content = "Result: " + systolic + "/" + diastolic + "   When: " + date;

            string results = result_record("Systolic", systolic, date) + result_record("Diastolic", diastolic, date);

            post_data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\"><title type=\"text\">" + title + "</title><content type=\"text\">" + content + "</content><ContinuityOfCareRecord xmlns='urn:astm-org:CCR'><Body><Results>" + results + "</Results></Body></ContinuityOfCareRecord></entry>";

            postHealthDataRequest();
        }

        //post authentication data
        private void authenticate()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link_client_login);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            request.BeginGetRequestStream(new AsyncCallback(getRequest), request);
        }

        //post request with authentication data
        private void getRequest(IAsyncResult asyncResult)
        {
            string postData = "accountType=" + accountType + "&Email=" + email + "&Passwd=" + password + "&service=" + service + "&source=" + source;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            Stream newStream = request.EndGetRequestStream(asyncResult);
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            request.BeginGetResponse(new AsyncCallback(getResponse), request);
        }

        //get response (AuthenticationToken) and get xml data
        private void getResponse(IAsyncResult asyncResult)
        {
            string responseFromServer = readResponse(asyncResult);
            AuthenticationToken = responseFromServer.Substring(responseFromServer.IndexOf("Auth=") + 5);

            getHealthDataRequest();
        }

        private string readResponse(IAsyncResult result)
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            WebResponse response = request.EndGetResponse(result);
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();
            return responseFromServer;
        }

        //build request 
        private void getHealthDataRequest()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);

            request.Method = "GET";
            request.Headers["Authorization"] = "GoogleLogin auth=" + AuthenticationToken;
            request.BeginGetResponse(new AsyncCallback(getHealthData), request);
        }

        //throw response event with data 
        private void getHealthData(IAsyncResult asyncResult)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                ccr_string_response = readResponse(asyncResult);

                getEvent(this, new GoogleGetEventArgs(ccr_string_response));

            });
        }

        //post request (new result)
        private void postHealthDataRequest()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/health/feeds/register/ui/" + profile_id);
            request.ContentType = "application/atom+xml";
            request.Method = "POST";
            request.Headers["Authorization"] = "GoogleLogin auth=" + AuthenticationToken;
            request.BeginGetRequestStream(new AsyncCallback(postHealthData), request);
        }

        //post request with data (new result)
        private void postHealthData(IAsyncResult asyncResult)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(post_data);

            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            Stream newStream = request.EndGetRequestStream(asyncResult);
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            request.BeginGetResponse(new AsyncCallback(postResponse), request);
        }

        //throw post response event with data 
        private void postResponse(IAsyncResult asyncResult)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                string responseFromServer = readResponse(asyncResult);

                postEvent(this, new GooglePostEventArgs(responseFromServer));
            });

        }

        //post data (as xml)
        private string result_record(string type, int value, string date)
        {
            return @"<Result>
	<DateTime>
		<Type>
			<Text>Collection start date</Text>
		</Type>
		<ExactDateTime>" + date + @"</ExactDateTime>
	</DateTime>
	<Description>
		<Text>" + type + @" Blood Pressure</Text>
	</Description>
	<Source>
		<Actor>
			<ActorID>" + email + @"</ActorID>
			<ActorRole>
				<Text>Patient</Text>
			</ActorRole>
		</Actor>
		<Actor>
			<ActorID>g" + email + @"</ActorID>
			<ActorRole>
				<Text>Patient</Text>
			</ActorRole>
		</Actor>
	</Source>
	<Test>
		<DateTime>
			<Type>
				<Text>Collection start date</Text>
			</Type>
			<ExactDateTime>" + date + @"</ExactDateTime>
		</DateTime>
		<Description>
			<Text>" + type + @" Blood Pressure</Text>
		</Description>
		<Source>
			<Actor>
				<ActorID>" + email + @"</ActorID>
				<ActorRole>
					<Text>Patient</Text>
				</ActorRole>
			</Actor>
		</Source>
		<TestResult>
			<Value>" + value + @"</Value>
			<Units>
				<Unit>mmHg</Unit>
			</Units>
		</TestResult>
	</Test>
</Result>";
        }

    }
}

/*
* http://blog.thycoticsolutions.com/2010/10/21/how-to-build-a-google-finance-client-app-with-windows-phone-7/
*/